import urllib2
import yaml
from os.path import dirname, abspath, join

import forest.main


def main(args):

    config = yaml.load(open(args.config).read())
    server = config.get('server')
    port = str(config.get('port'))
    uuid = config.get('uuid')



    if port and port != '80':
        name = ':'.join([server, port])
    else:
        name = server

    treefile_url_h = urllib2.urlopen(''.join(['http://', name, '/get-tree','?uuid=', uuid]))
    treefile_url = treefile_url_h.read()

    m = None

    try:

        args.root = '/'
        args.build = 'build'
        args.dry_run = False
        args.debug = True
        args.loglevel = "DEBUG"
        args.logfile = "-"
        m = forest.main.Main(args)

        m.set_sequence(forest.main.APPLY_SEQUENCE)
        m.set_root_only(False)
        m.set_config_file(treefile_url, prefix='/root')
        m.set_dry_run(args.dry_run)

        m.run()
    except Exception, e:
        print "Error: %s" % e
        raise
    else:
        if m:
            m.finish()
    finally:
        if m:
            m.finish()

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', required=True, help="Config file")
    args = parser.parse_args()
    main(args)
